package com.bezdelnick.forum.mail;

import com.bezdelnick.forum.mail.NotificationMailSender;
import com.bezdelnick.forum.mail.type.AbstractMail;
import com.bezdelnick.forum.mail.MailTemplatesRepository;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.ui.velocity.VelocityEngineUtils;

import javax.mail.internet.MimeMessage;
import java.io.StringWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: Bezdelnick
 * Date: 20.07.12
 * Time: 11:58
 * To change this template use File | Settings | File Templates.
 */
public class MailSendManager {
    private JavaMailSenderImpl sender;
    private VelocityEngine velocityEngine;
    private MailTemplatesRepository mailTemplates;

    private static final Logger LOGGER = LoggerFactory.getLogger(MailSendManager.class);

    public void sendMessage(final AbstractMail mail) {
        try {
            VelocityContext context = new VelocityContext();

            // Map to VelocityContext
            final Map<String, Object> mapContext = mail.getContext();
            /*Iterator iteratorKeys = mapContext.keySet().iterator();
            while (iteratorKeys.hasNext()) {
                String key = (String) iteratorKeys.next();
                context.put(key, mapContext.get(key));
            }

            //velocityEngine = new VelocityEngine();
            velocityEngine.init();

            Template template = velocityEngine.getTemplate((String) mailTemplates.getLetters().get(mail.getTemplateName()));

            StringWriter writer = new StringWriter();
            template.merge(context, writer);

            SimpleMailMessage simpleMessage = new SimpleMailMessage();
            simpleMessage.setSubject(mail.getSubject());
            simpleMessage.setTo(mail.getRecipients());
            simpleMessage.setText(writer.getBuffer().toString());
            simpleMessage.setSentDate(new Date());
            simpleMessage.setFrom("gofor.broake665@gmail.com");*/

            MimeMessagePreparator preparator = new MimeMessagePreparator() {
                public void prepare(MimeMessage mimeMessage) throws Exception {
                    MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
                    message.setTo(mail.getRecipients());
                    message.setFrom("gofor.broake665@gmail.com"); // could be parameterized...
                    //Map model = new HashMap();
                    //model.put("user", user);
                    String text = VelocityEngineUtils.mergeTemplateIntoString(
                            velocityEngine,
                            (String) mailTemplates.getLetters().get(mail.getTemplateName()),
                            mapContext
                    );
                    message.setText(text, true);
                }
            };

            //emailSender.send(simpleMessage);
            sender.send(preparator);
        } catch (MailException e) {
            LOGGER.warn(e.getMessage());
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
        }
    }

    public JavaMailSenderImpl getSender() {
        return sender;
    }

    public void setSender(JavaMailSenderImpl sender) {
        this.sender = sender;
    }

    public VelocityEngine getVelocityEngine() {
        return velocityEngine;
    }

    public void setVelocityEngine(VelocityEngine velocityEngine) {
        this.velocityEngine = velocityEngine;
    }

    public MailTemplatesRepository getMailTemplates() {
        return mailTemplates;
    }

    public void setMailTemplates(MailTemplatesRepository mailTemplates) {
        this.mailTemplates = mailTemplates;
    }
}
